package com.genius.adminmanager.role.controller;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.LinkedList;

import javax.servlet.http.HttpSession;

import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.genius.adminmanager.menu.entity.MenuJson;
import com.genius.adminmanager.other.entity.DataJson;
import com.genius.adminmanager.other.entity.RequestJson;
import com.genius.adminmanager.other.entity.ResponseJson;
import com.genius.adminmanager.other.entity.RoleMenuJson;
import com.genius.adminmanager.other.entity.SessionJson;
import com.genius.adminmanager.other.entity.TreeJson;
import com.genius.adminmanager.role.entity.RoleJson;
import com.genius.adminmanager.role.entity.RoleUrlJson;
import com.genius.adminmanager.role.service.RoleService;
import com.genius.adminmanager.user.entity.UserJson;
import com.genius.workflow.config.DefaultConfiguration;
import com.genius.workflow.ehcache.PowerUtil;
import com.genius.workflow.element.SQLBean;
import com.genius.workflow.log.ControllerLog;
import com.genius.workflow.page.PageResult;
import com.genius.workflow.util.ConnectionException;
import com.genius.workflow.util.DBClosedException;
import com.genius.workflow.util.DBTools;
import com.genius.workflow.util.DBTools2;
import com.genius.workflow.util.DBUtils;
import com.genius.workflow.util.GeniusJsonUtil;
import com.genius.workflow.util.Pattern;
import com.genius.workflow.util.TimeDiff;
import com.genius.workflow.util.TreeUtils;

/**
 * @Author: woy
 * @Description: 角色控制器
 * @param 
 */
@Controller
@RequestMapping("/adminmanager/role")
public class RoleController {
	/**
	 * 跳转到列表页面
	 * @param session
	 * @return
	 * @throws Exception
	 */
	@RequiresPermissions("68bce407d465464ebe6417d7140f2b42")
	@GetMapping("/toRoleList")
	public String toRoleList(){
		return "/views/adminmanager/role/rolelist";
	}
	/**
	 * 跳转到添加页面
	 * @param session
	 * @return
	 * @throws Exception
	 */
	@GetMapping("/toAddRole")
	public String toAddRole(){
		return "/views/adminmanager/role/addRole";
	}
	/**
	 * 切换角色页面
	 * @param session
	 * @return
	 * @throws Exception
	 */
	@GetMapping("/toChange")
	public String toChange(){
		return "/views/adminmanager/role/changeRole";
	}
	/**
	 * 切换门店页面
	 * @param session
	 * @return
	 * @throws Exception
	 */
	@GetMapping("/toChangeShopcode")
	public String toChangeShopcode(){
		return "/views/adminmanager/role/changeShopcode";
	}
	/**
	 * 获取当前用户的角色
	 * @param session
	 * @return
	 * @throws Exception
	 */
	@GetMapping("/getRoles")
	@ResponseBody
	public JSONObject getRoles(HttpSession session){
		JSONObject response = new JSONObject();
    	response.put(ResponseJson.code, ResponseJson.codeSuccess);
		JSONObject userJson = (JSONObject) SecurityUtils.getSubject().getPrincipal();
		//把当前用户放入session
		
		//根据用户查找相应的角色
		String whereField = UserJson.userId;
		String field = RoleJson.roleId+","+RoleJson.name;
		String table = "SELECT a.roleId,a.userId,b.name FROM t_user_role a left join t_role b on a.roleId=b.roleId";
		String jiaoseSql = DBTools.getSelectAndWhereSql(field, table,whereField);
		String [] jiaoseParms = DBTools.getSelectParms(whereField, userJson);
		
		try {
			JSONArray jiaoList = DBUtils.selectArr(jiaoseSql, jiaoseParms);
			if(jiaoList.size()==1){
				response.put(ResponseJson.status, ResponseJson.status_One_Role);
				response.put(ResponseJson.msg, ResponseJson.msg_One_Role);
				return response;
			}else if(jiaoList.size()>1){
				response.put(ResponseJson.status, ResponseJson.status_More_Role);
				response.put(ResponseJson.msg, ResponseJson.msg_More_Role);
				JSONObject resultJson = new JSONObject();
				resultJson.put("roles", jiaoList);
				String roleId = (String)session.getAttribute(SessionJson.roleId);
				resultJson.put("currentRole", roleId);
				resultJson.put(UserJson.command, userJson.getString(UserJson.command));
				response.put(ResponseJson.data, resultJson);
				
				return response;
			}
		} catch (ConnectionException e) {
            response.put(ResponseJson.status, ResponseJson.status_Failed);
            response.put(ResponseJson.msg, ResponseJson.msg_DB_Connect_Failed);
        } catch (DBClosedException e) {
            response.put(ResponseJson.status, ResponseJson.status_Failed);
            response.put(ResponseJson.msg, ResponseJson.msg_DB_Closed_Failed);
        } catch (SQLException e) {
            response.put(ResponseJson.status, ResponseJson.status_Failed);
            response.put(ResponseJson.msg, "SQL【"+jiaoseSql+"】执行异常,原因为【"+e.getMessage()+"】");
        }
		return response;
	}
	/**
	 * 添加操作
	 * @param session
	 * @return
	 * @throws Exception
	 */
	@ControllerLog(description="切换角色")
	@PostMapping("/changeRole")
	@ResponseBody
	public JSONObject changeRole(@RequestBody JSONObject json,HttpSession session){
		JSONObject response = new JSONObject();
    	response.put(ResponseJson.code, 0);
    	
    	String currendRoleId = json.getString(RoleJson.roleId);//切换后的roleId
    	if(currendRoleId == null){
    		response.put(ResponseJson.status, ResponseJson.status_Failed);
    		response.put(ResponseJson.msg, ResponseJson.msg_Error_Role);
    		return response;
    	}
    	response.put(ResponseJson.status, ResponseJson.status_Success);
		JSONObject userJson = (JSONObject) SecurityUtils.getSubject().getPrincipal();
		response.put(ResponseJson.loginUser, userJson);
		PowerUtil.loadEache(userJson,session,currendRoleId);
		RoleService.changeRoleSuccess(session, userJson, currendRoleId);
		//存入缓存
		
    	return response;
	}
	/**
	 * 获取图标数字
	 * @param session
	 * @return
	 * @throws Exception
	 */
	@ControllerLog(description="获取图标数字")
	@PostMapping("/getDaibanTubiao")
	@ResponseBody
	public JSONObject getDaibanTubiao(@RequestBody JSONObject json,HttpSession session){
		JSONObject response = new JSONObject();
    	response.put(ResponseJson.code, 0);
    	response.put(ResponseJson.status, ResponseJson.status_Success);
		//插入左侧菜单待办图标
		response.put("tubiao", RoleService.getDaibanTubiao(session,json));
		//存入缓存
		
    	return response;
	}
	/**
	 * 跳转到新增主页
	 * @param session
	 * @return
	 * @throws Exception
	 */
	@GetMapping("/toAddRoleUrl")
	public String toAddRoleUrl(){
		return "/views/adminmanager/role/addRoleUrl";
	}
	/**
	 * 获取角色下绑定的工作台路径地址
	 * @param session
	 * @return
	 * @throws Exception
	 */
	@ControllerLog(description="绑定主页地址")
	@PostMapping("/selectRoleUrls")
	@ResponseBody
	public JSONObject selectRoleUrls(@RequestBody JSONObject json,HttpSession session){
		JSONObject response = new JSONObject();
    	response.put(ResponseJson.code, 0);
//    	String roleId = json.getString(RoleJson.roleId);
    	String selectField = RoleUrlJson.id+","+RoleUrlJson.roleId+","+RoleUrlJson.url+","+RoleUrlJson.status;
    	String table = "t_role_url";
    	String whereField = RoleUrlJson.roleId;
    	try {
			JSONArray urls = DBTools2.selectArr(selectField, table, whereField, json);
			response.put(ResponseJson.status, ResponseJson.status_Success);
			response.put(ResponseJson.data, urls);
		}  catch (ConnectionException e) {
			response.put(ResponseJson.status, ResponseJson.status_Failed);
    		response.put(ResponseJson.msg, ResponseJson.msg_DB_Connect_Failed);
		} catch (DBClosedException e) {
			response.put(ResponseJson.status, ResponseJson.status_Failed);
    		response.put(ResponseJson.msg, ResponseJson.msg_DB_Closed_Failed);
		} catch (SQLException e) {
			response.put(ResponseJson.status, ResponseJson.status_Failed);
			response.put(ResponseJson.msg, ResponseJson.msg_Query_Data_Error);
		} 
    	return response;
	}
	/**
	 * 当前角色下进行新增主页地址
	 * @param session
	 * @return
	 * @throws Exception
	 */
	@ControllerLog(description="新增主页地址")
	@PostMapping("/addRoleUrls")
	@ResponseBody
	public JSONObject addRoleUrls(@RequestBody JSONObject json){
		JSONObject response = new JSONObject();
    	response.put(ResponseJson.code, 0);
    	
    	String insertField = RoleUrlJson.id+","+RoleUrlJson.roleId+","+RoleUrlJson.url;
    	
    	String table = "t_role_url";
    	try {
    		DBTools2.insert(insertField, table, json);
			response.put(ResponseJson.status, ResponseJson.status_Success);
			response.put(ResponseJson.msg, ResponseJson.msg_Add_Data_Success);
		}  catch (ConnectionException e) {
			response.put(ResponseJson.status, ResponseJson.status_Failed);
    		response.put(ResponseJson.msg, ResponseJson.msg_DB_Connect_Failed);
		} catch (DBClosedException e) {
			response.put(ResponseJson.status, ResponseJson.status_Failed);
    		response.put(ResponseJson.msg, ResponseJson.msg_DB_Closed_Failed);
		} catch (SQLException e) {
			response.put(ResponseJson.status, ResponseJson.status_Failed);
			response.put(ResponseJson.msg, ResponseJson.msg_Query_Data_Error);
		} 
    	return response;
	}
	/**
	 * 当前角色下进行新增主页地址
	 * @param session
	 * @return
	 * @throws Exception
	 */
	@ControllerLog(description="新增主页地址")
	@PostMapping("/detachRoleUrl")
	@ResponseBody
	public JSONObject detachRoleUrl(@RequestBody JSONObject json){
		JSONObject response = new JSONObject();
    	response.put(ResponseJson.code, 0);
    	
    	String whereDeleteField = RoleUrlJson.id;
    	String table = "t_role_url";
    	try {
    		DBTools2.deleteBach(whereDeleteField, table, json.getJSONArray(RequestJson.delData));
			response.put(ResponseJson.status, ResponseJson.status_Success);
			response.put(ResponseJson.msg, ResponseJson.msg_Del_Data_Success);
		}  catch (ConnectionException e) {
			response.put(ResponseJson.status, ResponseJson.status_Failed);
    		response.put(ResponseJson.msg, ResponseJson.msg_DB_Connect_Failed);
		} catch (DBClosedException e) {
			response.put(ResponseJson.status, ResponseJson.status_Failed);
    		response.put(ResponseJson.msg, ResponseJson.msg_DB_Closed_Failed);
		} catch (SQLException e) {
			response.put(ResponseJson.status, ResponseJson.status_Failed);
			response.put(ResponseJson.msg, ResponseJson.msg_Query_Data_Error);
		} 
    	return response;
	}
	/**
	 * 当前角色下进行授权主页地址
	 * @param session
	 * @return
	 * @throws Exception
	 */
	@ControllerLog(description="授权主页地址")
	@PostMapping("/permissonOperationRoleUrl")
	@ResponseBody
	public JSONObject permissonOperationRoleUrl(@RequestBody JSONObject json){
		JSONObject response = new JSONObject();
    	response.put(ResponseJson.code, 0);
    	
    	String updateField = RoleUrlJson.status;
    	String whereField_1 = RoleUrlJson.roleId;
    	String whereField_2 = RoleUrlJson.id+","+RoleUrlJson.roleId;
    	String table = "t_role_url";
    	try {
    		String id = json.getString(RoleUrlJson.id);
    		String status = json.getString(RoleUrlJson.status);
    		String roleId = json.getString(RoleUrlJson.roleId);
    		status = "confirm".equals(status)?"1":"0";
    		String update1 = DBTools.getUpdateAndWhereSql(updateField, table, whereField_1);
    		String update2 = DBTools.getUpdateAndWhereSql(updateField, table, whereField_2);
    		SQLBean bean1 = new SQLBean();
    		bean1.setSql(update1);
    		bean1.setParms(new String[]{"0",roleId});
    		
    		SQLBean bean2 = new SQLBean();
    		bean2.setSql(update2);
    		bean2.setParms(new String[]{status,id,roleId});
    		LinkedList<SQLBean> beans = new LinkedList();
    		beans.add(bean1);
    		beans.add(bean2);
    		DBTools2.updateBatch(beans);
			response.put(ResponseJson.status, ResponseJson.status_Success);
			response.put(ResponseJson.msg, ResponseJson.msg_Permission_Success);
		}  catch (ConnectionException e) {
			response.put(ResponseJson.status, ResponseJson.status_Failed);
    		response.put(ResponseJson.msg, ResponseJson.msg_DB_Connect_Failed);
		} catch (DBClosedException e) {
			response.put(ResponseJson.status, ResponseJson.status_Failed);
    		response.put(ResponseJson.msg, ResponseJson.msg_DB_Closed_Failed);
		} catch (SQLException e) {
			response.put(ResponseJson.status, ResponseJson.status_Failed);
			response.put(ResponseJson.msg, ResponseJson.msg_Permission_Error);
		} 
    	return response;
	}
	/**
	 * 查询数据
	 * @return
	 * @throws Exception
	 */
	@ControllerLog(description="查看用户列表数据")
	@PostMapping("/roleList")
	@ResponseBody
	public JSONObject roleList(@RequestBody JSONObject json,HttpSession session){
		JSONObject response = new JSONObject();
    	response.put(ResponseJson.code, 0);
    	String idValue = null;
    	if(!json.isEmpty()){
    		idValue = json.getString(TreeJson.pid);
    	}
//    	for(String str:request.getParameterMap().keySet()){
//    		if(!str.equals("{}")){
//    			JSONObject pidJson = JSONObject.parseObject(str);
//    			idValue = pidJson.getString(TreeJson.pid);
//    		}
//    	}
    	try {
    		String field = RoleJson.roleId+","+RoleJson.name+","+RoleJson.state+","+RoleJson.status+","+RoleJson.parentId;
    		String table = "t_role";
			JSONArray arr = TreeUtils.getOnceTree(RoleJson.roleId,idValue, field, table, RoleJson.resource,null,null);
			response.put(ResponseJson.status, ResponseJson.status_Success);
			response.put(ResponseJson.data, arr);
		} catch (ConnectionException e) {
			response.put(ResponseJson.status, ResponseJson.status_Failed);
    		response.put(ResponseJson.msg, ResponseJson.msg_DB_Connect_Failed);
		} catch (DBClosedException e) {
			response.put(ResponseJson.status, ResponseJson.status_Failed);
    		response.put(ResponseJson.msg, ResponseJson.msg_DB_Closed_Failed);
		} catch (SQLException e) {
			response.put(ResponseJson.status, ResponseJson.status_Failed);
			response.put(ResponseJson.msg, ResponseJson.msg_Query_Data_Error);
		} 
    	return response;
	}
	/**
	 * 跳转到添加页面
	 * @param session
	 * @return
	 * @throws Exception
	 */
	@GetMapping("/toAddUser")
	public String toAddUser(){
		return "/views/adminmanager/role/addUser";
	}
	/**
	 * 跳转到编辑页面
	 * @param session
	 * @return
	 * @throws Exception
	 */
	@GetMapping("/toEditRole")
	public String toEditRole(){
		return "/views/adminmanager/role/editRole";
	}
	/**
	 * 添加操作
	 * @param session
	 * @return
	 * @throws Exception
	 */
	@ControllerLog(description="添加角色")
	@PostMapping("/addRole")
	@ResponseBody
	public JSONObject addRole(@RequestBody JSONObject json,HttpSession session){
		
		JSONObject response = new JSONObject();
    	response.put(ResponseJson.code, 0);
		
		JSONObject userJson = (JSONObject)session.getAttribute(SessionJson.currentUser);
		String labelName = userJson.getString(UserJson.name);//获取当前创建者
		if(labelName==null){
			response.put(ResponseJson.status, ResponseJson.status_Failed);
    		response.put(ResponseJson.msg, ResponseJson.msg_Session_Failure);
    		return response;
		}
		json.put(RoleJson.createAuthor, labelName);
		
		String roleId = json.getString(RoleJson.roleId);
		String status = json.containsKey(RoleJson.status)?"1":"0";
		String createTime = TimeDiff.getNowTime(Pattern.yyyyMMddHHmmss);
		json.put(RoleJson.status, status);
		json.put(RoleJson.createTime, createTime);
		
		String table = "t_role";
		String insertField = RoleJson.roleId+","+RoleJson.name+","+RoleJson.state+","+RoleJson.status+","+RoleJson.parentId
				+","+RoleJson.createAuthor+","+RoleJson.createTime; 
		try {
			if(roleId.equals("1")){
				//说明是根目录下,直接插入
				json.put(RoleJson.parentId, "-1");//pid为-1
				json.put(RoleJson.status, "1");//层级为1
				TreeUtils.addTree(insertField, table, json);
			}else{
				//根据菜单先查找上层相关信息
				String selectState = "select "+RoleJson.state+" from "+table+" where "+RoleJson.roleId+"=?";
				
				JSONObject stateJsonG = DBUtils.select(selectState, new String[]{roleId});
				int stateP = stateJsonG.getInteger(RoleJson.state);
				//在上层的基础上+1
				int nowState = stateP+1;
				json.put(RoleJson.parentId, roleId);//pid为-1
				json.put(RoleJson.state, nowState);
				TreeUtils.addTree(insertField, table, json);
			}
			response.put(ResponseJson.status, ResponseJson.status_Success);
			response.put(ResponseJson.msg, ResponseJson.msg_Add_Data_Success);
		}  catch (ConnectionException e) {
			response.put(ResponseJson.status, ResponseJson.status_Failed);
    		response.put(ResponseJson.msg, ResponseJson.msg_DB_Connect_Failed);
		} catch (DBClosedException e) {
			response.put(ResponseJson.status, ResponseJson.status_Failed);
    		response.put(ResponseJson.msg, ResponseJson.msg_DB_Closed_Failed);
		} catch (SQLException e) {
			response.put(ResponseJson.status, ResponseJson.status_Failed);
			response.put(ResponseJson.msg, ResponseJson.msg_Add_Data_Error);
		}
		return response;
	}
	/**
	 * 编辑操作
	 * @param session
	 * @return
	 * @throws Exception
	 */
	@ControllerLog(description="编辑角色")
	@PostMapping("/editRole")
	@ResponseBody
	public JSONObject editRole(@RequestBody JSONObject json, HttpSession session){
		JSONObject response = new JSONObject();
    	response.put(ResponseJson.code, 0);
    	JSONObject userJson = (JSONObject)session.getAttribute(SessionJson.currentUser);
		String labelName = userJson.getString(UserJson.name);//获取当前创建者
		if(labelName==null){
			response.put(ResponseJson.status, ResponseJson.status_Failed);
    		response.put(ResponseJson.msg, ResponseJson.msg_Session_Failure);
    		return response;
		}
		String createTime = TimeDiff.getNowTime(Pattern.yyyyMMddHHmmss);
		String status = json.containsKey(MenuJson.status)?"1":"0";
		
		json.put(RoleJson.status, status);
		json.put(RoleJson.createTime, createTime);
		json.put(RoleJson.createAuthor, labelName);
		
		String updateField = RoleJson.name+","+RoleJson.createAuthor+","+RoleJson.createTime+","+RoleJson.status;
		String whereField = RoleJson.roleId;
		
		try {
			DBTools.update(updateField, whereField, "t_role", json);
			response.put(ResponseJson.status, ResponseJson.status_Success);
			response.put(ResponseJson.msg, ResponseJson.msg_Edit_Data_Success);
		}  catch (ConnectionException e) {
			response.put(ResponseJson.status, ResponseJson.status_Failed);
    		response.put(ResponseJson.msg, ResponseJson.msg_DB_Connect_Failed);
		} catch (DBClosedException e) {
			response.put(ResponseJson.status, ResponseJson.status_Failed);
    		response.put(ResponseJson.msg, ResponseJson.msg_DB_Closed_Failed);
		} catch (SQLException e) {
			response.put(ResponseJson.status, ResponseJson.status_Failed);
			response.put(ResponseJson.msg, ResponseJson.msg_Edit_Data_Error);
		}
    	return response;
	}
	/**
	 * 删除操作
	 * @param session
	 * @return
	 * @throws Exception
	 */
	
	@ControllerLog(description="删除角色")
	@PostMapping("/batchdelRole")
	@ResponseBody
	public JSONObject batchdelRole(@RequestBody JSONObject json){
		JSONObject response = new JSONObject();
		try {
			TreeUtils.delByIdTree("t_role", RoleJson.roleId, RoleJson.parentId,json );
			response.put(ResponseJson.status, ResponseJson.status_Success);
			response.put(ResponseJson.msg, ResponseJson.msg_Del_Data_Success);
		}  catch (ConnectionException e) {
			response.put(ResponseJson.status, ResponseJson.status_Failed);
    		response.put(ResponseJson.msg, ResponseJson.msg_DB_Connect_Failed);
		} catch (DBClosedException e) {
			response.put(ResponseJson.status, ResponseJson.status_Failed);
    		response.put(ResponseJson.msg, ResponseJson.msg_DB_Closed_Failed);
		} catch (SQLException e) {
			response.put(ResponseJson.status, ResponseJson.status_Failed);
			response.put(ResponseJson.msg, ResponseJson.msg_Del_Data_Error);
		}
		response.put(ResponseJson.code, 0);
		return response;
	}
	@GetMapping("/queryTreeList")
	@ResponseBody
	public JSONObject queryTreeList(HttpSession session){
		String field = RoleJson.roleId+","+RoleJson.name+","+RoleJson.state+","+RoleJson.status;
    	String table = "t_role";
    	JSONObject response = new JSONObject();
    	response.put(ResponseJson.code, 0);
		try {
			JSONArray data = TreeUtils.getTree(RoleJson.roleId, field,RoleJson.parentId, table, RoleJson.state, RoleJson.resource,null,null);
			
			JSONArray root = new JSONArray();
			
			JSONArray root1Arr = new JSONArray();
			JSONObject root1 = new JSONObject();
			root1.put("value", "-1");
			root1.put("name", "根节点");
			for(int i = 0;i<data.size();i++){
				JSONObject datas = data.getJSONObject(i);
				datas.put("value", datas.getString(RoleJson.roleId));
				datas.put("name", datas.getString(RoleJson.name));
				JSONArray children = new JSONArray();
				for(int index = 0;index<datas.getJSONArray("children").size();index++){
					JSONObject childrens = changeKey(datas.getJSONArray("children").getJSONObject(index));
					children.add(childrens);
				}
				datas.put("children", children);
				root1Arr.add(removeKey(datas));
			}
			
			root1.put("children", root1Arr);
			root.add(root1);
			response.put(ResponseJson.status, ResponseJson.status_Success);
			response.put(ResponseJson.data, root);
			
		} catch (ConnectionException e) {
			response.put(ResponseJson.status, ResponseJson.status_Failed);
    		response.put(ResponseJson.msg, ResponseJson.msg_DB_Connect_Failed);
		} catch (DBClosedException e) {
			response.put(ResponseJson.status, ResponseJson.status_Failed);
    		response.put(ResponseJson.msg, ResponseJson.msg_DB_Closed_Failed);
		} catch (SQLException e) {
			response.put(ResponseJson.status, ResponseJson.status_Failed);
			response.put(ResponseJson.msg, ResponseJson.msg_Query_Data_Error);
		}
    	
		return response;
	}
	private JSONObject changeKey(JSONObject datas){
		datas.put("value", datas.getString(RoleJson.roleId));
		datas.put("name", datas.getString(RoleJson.name));
		
		if(datas.containsKey("children")){
			JSONArray children = new JSONArray();
			for(int index = 0;index<datas.getJSONArray("children").size();index++){
				JSONObject childrens = changeKey(datas.getJSONArray("children").getJSONObject(index));
				//三级目录 去掉按钮 一级
				if(childrens != null){
					children.add(childrens);
					if(childrens.containsKey("children")){
						if(childrens.getJSONArray("children").size()==0)
							childrens.remove("children");
					}
				}
			}
				datas.put("children", children);
		}
		
		return removeKey(datas);
	}
	private JSONObject removeKey(JSONObject datas){
		String keys = "value,name,children";
		ArrayList<String> removeKeys = new ArrayList<>();
		for(String key:datas.keySet()){
			if(!keys.contains(key)){
				removeKeys.add(key);
			}
		}
		for(String key:removeKeys){
			datas.remove(key);
		}
		return datas;
	}
	/**
	 * 根据角色查询对应的菜单
	 * @param json
	 * @return
	 */
	@PostMapping("/selectMenuByRole")
	@ResponseBody
	public JSONObject selectMenuByRole(@RequestBody JSONObject json){
		JSONObject response = new JSONObject();
		response.put(ResponseJson.code, 0);
		
		String roleId = json.getString(RoleJson.roleId);
		String menuIdsSql = "select menuId from t_role_menu where "+RoleJson.roleId+"=?";
		
		try {
			JSONArray menuIds = DBUtils.selectArr(menuIdsSql, new String[]{roleId});
			
			String [] menuIdsStr = GeniusJsonUtil.getFieldByDouHaoArr(menuIds, MenuJson.menuId);
			//先获取菜单的树形列表
			String menuField = MenuJson.menuId+","+MenuJson.name+","+MenuJson.state;
			String table = "t_menu";
			String idValue = json.getString(TreeJson.pid);
			JSONArray menuArr = TreeUtils.getOnceTreeAndPermission(MenuJson.menuId,idValue, menuField, table, MenuJson.resource,menuIdsStr, null, null);
			response.put(ResponseJson.status, ResponseJson.status_Success);
			response.put(ResponseJson.data, menuArr);
		} catch (ConnectionException e) {
			response.put(ResponseJson.status, ResponseJson.status_Failed);
    		response.put(ResponseJson.msg, ResponseJson.msg_DB_Connect_Failed);
		} catch (DBClosedException e) {
			response.put(ResponseJson.status, ResponseJson.status_Failed);
    		response.put(ResponseJson.msg, ResponseJson.msg_DB_Closed_Failed);
		} catch (SQLException e) {
			response.put(ResponseJson.status, ResponseJson.status_Failed);
			response.put(ResponseJson.msg, ResponseJson.msg_Del_Data_Error);
		}
		
		return response;
	}
	/**
	 * 授权菜单操作
	 * @param json
	 * @return
	 */
	@ControllerLog(description="授权菜单")
	@PostMapping("/permissionOperation")
	@ResponseBody
	public JSONObject permissionOperation(@RequestBody JSONObject json){
		JSONObject response = new JSONObject();
		response.put(ResponseJson.code, 0);
		String menuId = json.getString(MenuJson.menuId);
		String roleID = json.getString(RoleJson.roleId);
		
		//将menuId转换成jonsarr，批量执行，照顾批量授权
		String [] menuIds = menuId.split(DefaultConfiguration.separator_douhao);
		JSONArray menuIdsArr = new JSONArray();
		for(String id:menuIds){
			JSONObject menuIdJson = new JSONObject();
			menuIdJson.put(MenuJson.menuId, id);
			menuIdJson.put(RoleJson.roleId, roleID);
			menuIdsArr.add(menuIdJson);
		}
		RoleMenuJson.Type operation = RoleMenuJson.Type.valueOf(json.getString(RoleMenuJson.operation));
		try {
			String table = "t_role_menu";
			String field = RoleMenuJson.menuId+","+RoleMenuJson.roleId;
			switch(operation){
				case confirm:
					DBTools.insertBatch(field, table, menuIdsArr);
					break;
				case cancle:
					DBTools.deleteBach(field, table, menuIdsArr);
					break;
			}
			//无论哪种授权，完成后都要刷新powerUtil
			PowerUtil.updatePower();
			response.put(ResponseJson.status, ResponseJson.status_Success);
			response.put(ResponseJson.msg, ResponseJson.msg_Permission_Success);
		}  catch (ConnectionException e) {
			response.put(ResponseJson.status, ResponseJson.status_Failed);
    		response.put(ResponseJson.msg, ResponseJson.msg_DB_Connect_Failed);
		} catch (DBClosedException e) {
			response.put(ResponseJson.status, ResponseJson.status_Failed);
    		response.put(ResponseJson.msg, ResponseJson.msg_DB_Closed_Failed);
		} catch (SQLException e) {
			response.put(ResponseJson.status, ResponseJson.status_Failed);
			response.put(ResponseJson.msg, ResponseJson.msg_Permission_Error);
		}		return response;
	}
	/**
	 * 授权数据操作
	 * @param json
	 * @return
	 */
	@ControllerLog(description="授权角色")
	@PostMapping("/selectMenuDataByRole")
	@ResponseBody
	public JSONObject selectMenuDataByRole(@RequestBody JSONObject json){
		JSONObject response = new JSONObject();
		response.put(ResponseJson.code, 0);
		String roleId = json.getString(RoleJson.roleId);
		
		String table = "t_role_menu";
		String role_menu_field = MenuJson.menuId;
		String where = RoleJson.roleId;
		String select = DBTools.getSelectAndWhereSql(role_menu_field, table, where);
		String [] parms = DBTools.getSelectParms(where, json);
		try {
//			JSONArray menuIdsArr = DBUtils.selectArr(select, parms);
			String menu_field_table = "t_menu_field";
			String sql = "select a."+MenuJson.menuId+","+"b."+MenuJson.name+",a."+MenuJson.field+" from "+menu_field_table+" a,t_menu b where a."+MenuJson.menuId+" in("+select+") and a."+MenuJson.menuId+"=b."+MenuJson.menuId;
			JSONArray arr = DBUtils.selectArr(sql, parms);
			
			JSONArray result = new JSONArray();
			for(int i=0;i<arr.size();i++){
				JSONObject jsonA = arr.getJSONObject(i);
				JSONObject jsonB = new JSONObject();
				String menuId = jsonA.getString(MenuJson.menuId);
				//根据menuId和roleId 去找字段
				String t_data = "t_data";
				String t_data_field = DataJson.field;
				String t_data_where_field = RoleJson.roleId+","+MenuJson.menuId;
				String t_data_sql = DBTools.getSelectAndWhereSql(t_data_field, t_data, t_data_where_field);
				String [] t_data_parms = new String[]{roleId,menuId};
				JSONObject t_data_field_rs = DBUtils.select(t_data_sql, t_data_parms);
				String t_data_field_rs_exist = t_data_field_rs==null?"":t_data_field_rs.getString(DataJson.field);
				
				jsonB.put(MenuJson.menuId, menuId);
				jsonB.put(MenuJson.name, jsonA.getString(MenuJson.name));
				boolean isHas = false;
				
				JSONArray jsonC = new JSONArray();
				String [] fields = !StringUtils.equalsIgnoreCase(jsonA.getString(MenuJson.field), null)?jsonA.getString(MenuJson.field).split(DefaultConfiguration.separator_douhao):new String[]{};
				for(int g=0;g<fields.length;g++){
					JSONObject newJson = new JSONObject();
					String shouquan_field = fields[g];
					if(t_data_field_rs_exist.contains(shouquan_field)){
						newJson.put("permissionStatus", "1");
						isHas = true;
					}else
						newJson.put("permissionStatus", "0");
						
					newJson.put(MenuJson.menuId, menuId+g);//为了形成树，把主键menuId当成了dataId
					newJson.put(DataJson.dataId, menuId);//实际上dataId才是真正的menuId
					newJson.put(MenuJson.name, fields[g]);
					jsonC.add(newJson);
				}
				jsonB.put(DataJson.dataId, "0");////实际上dataId才是真正的menuId 为0说明是真正的菜单，不是字段了
				jsonB.put("permissionStatus", isHas?"1":"0");
				jsonB.put("children", jsonC);
				result.add(jsonB);
			}
			response.put(ResponseJson.status, ResponseJson.status_Success);
			response.put(ResponseJson.data, result);
			
		} catch (ConnectionException e) {
			response.put(ResponseJson.status, ResponseJson.status_Failed);
    		response.put(ResponseJson.msg, ResponseJson.msg_DB_Connect_Failed);
		} catch (DBClosedException e) {
			response.put(ResponseJson.status, ResponseJson.status_Failed);
    		response.put(ResponseJson.msg, ResponseJson.msg_DB_Closed_Failed);
		} catch (SQLException e) {
			response.put(ResponseJson.status, ResponseJson.status_Failed);
			response.put(ResponseJson.msg, ResponseJson.msg_Query_Data_Error);
		}
		
		return response;
	}
	/**
	 * 授权数据操作
	 * @param json
	 * @return
	 */
	@ControllerLog(description="授权数据")
	@PostMapping("/permissionOperationData")
	@ResponseBody
	public JSONObject permissionOperationData(@RequestBody JSONObject json){
		JSONObject response = new JSONObject();
		response.put(ResponseJson.code, 0);
		//授权的菜单名称
		String name = json.getString(MenuJson.name);
		String roleId = json.getString(RoleJson.roleId);
		String menuId = json.getString(MenuJson.menuId);
		
		//将menuId转换成jonsarr，批量执行，照顾批量授权
		//数据的批量授权，肯定一一相等，一一对应
		//已经在前端做了处理，只能是同时授权同一个菜单下的字段，且要么是同时授权，要么是同时取消，不能一个授权一个取消
//		JSONArray jsonArr = new JSONArray();
		String [] menuIds = menuId.split(DefaultConfiguration.separator_douhao);
		String [] names = name.split(DefaultConfiguration.separator_douhao);
		
		
		RoleMenuJson.Type operation = RoleMenuJson.Type.valueOf(json.getString(RoleMenuJson.operation));
		String t_data_table = "t_data";
		String selectField = DataJson.field;
		String whereField = MenuJson.menuId+","+RoleJson.roleId;
		String sql = DBTools.getSelectAndWhereSql(selectField, t_data_table, whereField);
		try {
			String [] exist_parms = new String[]{menuIds[0],roleId};
			JSONObject existJson = DBUtils.select(sql, exist_parms);
			String existStr = existJson==null?"":existJson.getString(DataJson.field);
			JSONObject dataJson = new JSONObject();
			switch(operation){
				case confirm:
					String newStr = GeniusJsonUtil.addToStringArr(names, existStr);
					dataJson.put(DataJson.field, newStr);
					dataJson.put(MenuJson.menuId, menuIds[0]);
					dataJson.put(RoleJson.roleId, roleId);
					
					RoleService.addFieldByMenuId(dataJson);
					break;
				case cancle:
					dataJson.put(MenuJson.menuId, menuIds[0]);
					String cutStr = GeniusJsonUtil.cutToStringArr(names, existStr);
					dataJson.put(DataJson.field, cutStr);
					dataJson.put(RoleJson.roleId, roleId);
					dataJson.put(MenuJson.menuId, menuIds[0]);
					RoleService.addFieldByMenuId(dataJson);
					break;
			}
			response.put(ResponseJson.status, ResponseJson.status_Success);
			response.put(ResponseJson.msg, ResponseJson.msg_Permission_Success);
		} catch (ConnectionException e) {
			response.put(ResponseJson.status, ResponseJson.status_Failed);
    		response.put(ResponseJson.msg, ResponseJson.msg_DB_Connect_Failed);
		} catch (DBClosedException e) {
			response.put(ResponseJson.status, ResponseJson.status_Failed);
    		response.put(ResponseJson.msg, ResponseJson.msg_DB_Closed_Failed);
		} catch (SQLException e) {
			response.put(ResponseJson.status, ResponseJson.status_Failed);
			response.put(ResponseJson.msg, ResponseJson.msg_Query_Data_Error);
		}
		return response;
	}
	/**
	 * 查看授权人员信息
	 * @param json
	 * @return
	 */
	@PostMapping("/selectUserByRole")
	@ResponseBody
	public JSONObject selectUserByRole(@RequestBody JSONObject json){
		JSONObject response = new JSONObject();
		response.put(ResponseJson.code, 0);
		String field = UserJson.userId;
		String where = RoleJson.roleId;
		String table = "t_user_role";
		String selectSql = DBTools.getSelectAndWhereSql(field, table, where)+" group by "+field;
		String [] params = DBTools.getSelectParms(where, json);
		try {
			JSONArray userArr = DBTools.selectArr(selectSql, params);
			String userId = "";
			if(userArr.size()>0){
				userId = GeniusJsonUtil.getFieldByDouHao(userArr, field);
			}else{
				response.put(ResponseJson.status, ResponseJson.status_Success);
	    		response.put(ResponseJson.data, new JSONObject());
	    		return response;
			}
			String where_append = field+" in ("+userId+")";
			
			JSONObject search = new JSONObject();
			search.put(PageResult.whereKey, UserJson.userId);
			search.put(PageResult.whereValue, where_append);
			json.put(PageResult.highSearch, search);
			
			String headField = UserJson.userId+","+UserJson.username+","+UserJson.name;
			json.remove(RoleJson.roleId);
			json.put(DataJson.field, headField);
			String selectUser = "select "+headField+" FROM t_user  where userId!='000' and status=1 and "+where_append;
			JSONArray data = DBTools.selectArr(selectUser);
			
			response.put(ResponseJson.status, ResponseJson.status_Success);
    		response.put(ResponseJson.data, data);
		} catch (ConnectionException e) {
			response.put(ResponseJson.status, ResponseJson.status_Failed);
    		response.put(ResponseJson.msg, ResponseJson.msg_DB_Connect_Failed);
		} catch (DBClosedException e) {
			response.put(ResponseJson.status, ResponseJson.status_Failed);
    		response.put(ResponseJson.msg, ResponseJson.msg_DB_Closed_Failed);
		} catch (SQLException e) {
			response.put(ResponseJson.status, ResponseJson.status_Failed);
			response.put(ResponseJson.msg, ResponseJson.msg_Query_Data_Error);
		}
		return response;
	}
    
    
	/**
	 * 跳转到弹出层
	 * @param session
	 * @return
	 * @throws Exception
	 */
	@GetMapping("/toTransfor")
	public String toTransfor(){
		return "/views/adminmanager/role/transfor";
	}
	/**
	 * 添加时查看授权人员
	 * @param json
	 * @return
	 */
	@PostMapping("/queryPermissionPerson")
	@ResponseBody
	public JSONObject queryPermissionPerson(@RequestBody JSONObject json){
		JSONObject response = new JSONObject();
		response.put(ResponseJson.code, 0);
		String userField = UserJson.userId+","+UserJson.username+","+UserJson.name+","+UserJson.phone;
	//	String userField = UserJson.userId+" value,"+UserJson.name+" title,"+UserJson.groupId;
		String userTable = "t_user";
		
		String selectUser = DBTools.getSelectSql(userField, userTable);
		String role_user_table = "t_user_role";
		String role_user_field = UserJson.userId;
		String where = RoleJson.roleId;
		String selectRoleUser = DBTools.getSelectAndWhereSql(role_user_field, role_user_table, where);
		selectUser = selectUser+" where "+UserJson.userId+" not in("+selectRoleUser+") and userId !=000 ";
		try {
			//初始数据为
			String [] parms = DBTools.getSelectParms(where, json);
			JSONArray userArr = DBUtils.selectArr(selectUser,parms);
			
			response.put(ResponseJson.data, userArr);
			response.put(ResponseJson.status, ResponseJson.status_Success);
			
		} catch (ConnectionException e) {
			response.put(ResponseJson.status, ResponseJson.status_Failed);
    		response.put(ResponseJson.msg, ResponseJson.msg_DB_Connect_Failed);
		} catch (DBClosedException e) {
			response.put(ResponseJson.status, ResponseJson.status_Failed);
    		response.put(ResponseJson.msg, ResponseJson.msg_DB_Closed_Failed);
		} catch (SQLException e) {
			response.put(ResponseJson.status, ResponseJson.status_Failed);
			response.put(ResponseJson.msg, ResponseJson.msg_Query_Data_Error);
		}		
		return response;
	}
	/**
	 * 授权人员操作
	 * @param json
	 * @return
	 */
	@PostMapping("/permissionOperationPerson")
	@ResponseBody
	public JSONObject permissionOperationPerson(@RequestBody JSONObject json){
		JSONObject response = new JSONObject();
		response.put(ResponseJson.code, 0);
		JSONArray userIdArr = json.getJSONArray(UserJson.userId);
		String roleID = json.getString(RoleJson.roleId);
		JSONArray userIdResult = new JSONArray();
		for(int i=0;i<userIdArr.size();i++){
			JSONObject user = new JSONObject();
			user.put(UserJson.userId, userIdArr.getString(i));
			user.put(RoleJson.roleId, roleID);
			userIdResult.add(user);
		}
		RoleMenuJson.Type operation = RoleMenuJson.Type.valueOf(json.getString(RoleMenuJson.operation));
		try {
			String table = "t_user_role";
			String field = UserJson.userId+","+RoleJson.roleId;
			switch(operation){
				case AddUser:
//					String insertSql = DBTools.getReplaceInsertSql(field, table);
//					List<String[]> insertParms = DBTools.getInsertListParms(field, userIdResult);
//					DBUtils.InsertBatch(insertSql, insertParms);
//					DBTools.insert(insertField, table, json)
					RoleService.addUserByRoleId(userIdResult);
					break;
				case DetachUser:
//					String updateSql = DBTools.getDelSqlAndWhere(table, field);
//					List<String[]> delParms = DBTools.getDeleteListParms(field, userIdResult);
//					DBUtils.delBatch(updateSql, delParms);
					DBTools.deleteBach(field, table, userIdResult);
					break;
			}
			response.put(ResponseJson.status, ResponseJson.status_Success);
			response.put(ResponseJson.msg, ResponseJson.msg_Permission_Success);
		}  catch (ConnectionException e) {
			response.put(ResponseJson.status, ResponseJson.status_Failed);
    		response.put(ResponseJson.msg, ResponseJson.msg_DB_Connect_Failed);
		} catch (DBClosedException e) {
			response.put(ResponseJson.status, ResponseJson.status_Failed);
    		response.put(ResponseJson.msg, ResponseJson.msg_DB_Closed_Failed);
		} catch (SQLException e) {
			response.put(ResponseJson.status, ResponseJson.status_Failed);
			response.put(ResponseJson.msg, ResponseJson.msg_Permission_Error);
		}		return response;
	}
}
